package cn.xiaohuodui.utils.json;

import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.junit.Test;

import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

/**
 * Author :chenqisheng
 * Date   :15/3/30.
 */
public class JsonUtil {
    private static final JsonSeriaziler JSON = new JsonSeriaziler();

    private static final JsonSeriaziler WITHNULL = new JsonSeriaziler(SerializerFeature.WriteMapNullValue);     //设置不忽略null

    public static String seriazileAsString(Object object) {
        return JSON.seriazileAsString(object);
    }

    public static <T> T deserializeAsObject(String jsonString, Type clazz) {
        return JSON.deserializeAsObject(jsonString, clazz);
    }

    public static <T> List<T> deserializeAsList(String jsonString, Class clazz) {
        final List<T> jsonResponse = com.alibaba.fastjson.JSON.parseArray(jsonString, clazz);
        return jsonResponse;
    }

    public static Map deserializeAsMap(String jsonString) {
        return (Map) com.alibaba.fastjson.JSON.parse(jsonString);
    }

    /**
     * Obj转Json  不忽略null的属性
     *
     * @param object
     * @param
     * @return
     */
    public static String seriazileAsStringWithNull(Object object) {
        return WITHNULL.seriazileAsString(object);
    }


    /**
     * 将一个对象，转换成对象
     *
     * @param obj 只能是Object或者Map，不能是数组类型
     * @return
     */
    public static Map<String, Object> toJsonMap(Object obj) {
        if (obj == null)
            return null;
        String objString = com.alibaba.fastjson.JSON.toJSONString(obj);
        return com.alibaba.fastjson.JSON.parseObject(objString, getType());
    }

    private static Type getType() {
        return new TypeReference<Map<String, Object>>() {
        }.getType();
    }
}
